#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from rest_framework import serializers
from .models import Teacher, Student, Achievement, Course

"""
序列化器嵌套，
    1、单层嵌套序列化器中使用序列化器
        s_achievement = AchievementModelSerializer(many=True)
    2、序列化器中套用单个字段
        course_name = serializers.CharField(source="course.name")  # 单个的时候这样写
        teacher_name = serializers.CharField(source="course.teacher.name")
    
        class Meta:
            model = Achievement
            fields = ["id", "score", "course_name", "teacher_name", "create_dtime"]
    3、指定嵌套
        class Meta:
            model = Achievement
            fields = "__all__"
            depth = 2
    4、可以执行调用模型的方法
         s_achievement = AchievementModelSerializer(many=True)  # 嵌套序列化器，把成绩的序列化器也初始化之后给到学生表中当做额外的字段作为返回值
        class Meta:
            model = Student
            # fields = ["id", "name", "s_achievement"]  # 字段不能乱加 必须和外键一致
            # depth = 1
            fields = ["id", "name", "achievement", "s_achievement"]  # achievement 可以调用模型类中方法中返回的数据
"""


class CourseModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Course
        # fields = ["id", "name", "teacher"] # 返回多个数据
        fields = ["name"]


class AchievementModelSerializer2(serializers.ModelSerializer):
    # course = CourseModelSerializer()
    course_name = serializers.CharField(source="course.name")  # 单个的时候这样写
    teacher_name = serializers.CharField(source="course.teacher.name")

    class Meta:
        model = Achievement
        fields = ["id", "score", "course_name", "teacher_name", "create_dtime"]


class AchievementModelSerializer(serializers.ModelSerializer):
    # course = CourseModelSerializer()
    # course_name = serializers.CharField(source="course.name")  # 单个的时候这样写
    # teacher_name = serializers.CharField(source="course.teacher.name")

    class Meta:
        model = Achievement
        fields = "__all__"
        depth = 2
        # fields = ["id", "score", "course_name", "teacher_name", "create_dtime"]


class StudentModelSerializer(serializers.ModelSerializer):
    """学生序列化器"""
    s_achievement = AchievementModelSerializer(many=True)  # 嵌套序列化器，把成绩的序列化器也初始化之后给到学生表中当做额外的字段作为返回值

    class Meta:
        model = Student
        # fields = ["id", "name", "s_achievement"]  # 字段不能乱加 必须和外键一致
        # depth = 1
        fields = ["id", "name", "achievement", "s_achievement"]  # achievement 可以调用模型类中方法中返回的数据


class StudentModelSerializer2(serializers.ModelSerializer):
    """学生序列化器"""
    s_achievement = AchievementModelSerializer(many=True)  # 嵌套序列化器，把成绩的序列化器也初始化之后给到学生表中当做额外的字段作为返回值

    class Meta:
        model = Student
        fields = ["id", "name", "s_achievement"]  # 字段不能乱加 必须和外键一致


class TeacherModelSerializer(serializers.ModelSerializer):
    """教师序列化器"""

    class Meta:
        model = Teacher
        fields = "__all__"
